const state = {
  // 规定默认存在的页面，isDefault为true，不允许删除；isSelect控制当前选中的状态；
  tabRoutes: [{ name: '首页', path: '/home', key: 'home', isDefault: true, isSelect: false }],
  currentRoute: '', // 当前选中
};

const mutations = {
  setTabRoutes: (state, routes) => {
    // 判断当前标签是否存在，存在改变选中状态，不存在则添加
    const isExist = state.tabRoutes.filter(item => item.name == routes.meta.title)
    state.tabRoutes.forEach(element => {
      if (element.name == routes.meta.title) {
        state.currentRoute = element.key
        element.isSelect = true
      } else {
        element.isSelect = false
      }
    });
    if (isExist.length == 0) {
      state.currentRoute = routes.name
      state.tabRoutes.push({
        name: routes.meta.title,
        path: routes.path,
        key: routes.name,
        isDefault: false,
        isSelect: true,
      });
    }
  },
  removeTabRoutes: (state, routes) => {
    const num = state.tabRoutes.findIndex(item => item.name == routes.name)
    state.tabRoutes.splice(num, 1)

    const len = state.tabRoutes.length;
    state.currentRoute = state.tabRoutes[len - 1].key
  },
  cleanTabRoutes: (state, routes) => {
    state.tabRoutes = routes
  }
};

const actions = {
  // 添加路由
  addTabRoutes({ commit }, roles) {
    return new Promise(resolve => {
      commit("setTabRoutes", roles);
      resolve();
    });
  },
  // 删除路由
  removeTabRoutes({ commit }, roles) {
    return new Promise(resolve => {
      commit("removeTabRoutes", roles);
      resolve();
    });
  },
  // 模拟清空令牌和角色状态
  resetTabRoutes({ commit }) {
    return new Promise(resolve => {
      commit("cleanTabRoutes", []);
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};